package com.sugar.psych.assessment.module.business.util;

import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sugar.psych.assessment.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.psych.assessment.module.business.enums.ErrorCodeConstants.AI_CHAT_REPLY_ERROR;

/**
 * @author Y.sugar
 * @since 2025/6/17 10:16
 */
@Slf4j
public class DeepSeekUtil {

    private static final WebClient WEB_CLIENT = WebClient.create("https://api.deepseek.com");

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Message {

        /**
         * 消息内容
         */
        private String content;
        /**
         * 角色：user用户 system系统 assistant智能体
         */
        private String role;
    }

    public static Flux<String> chatStream(String chatContent) {
        try {
            Map<String, Object> params = new HashMap<>();
            List<Message> messages = new ArrayList<>();
            messages.add(new Message("你是一位心理咨询师，用来解答用户关于心理咨询的问题！", "system"));
            messages.add(new Message(chatContent, "user"));
            params.put("messages", messages);
            params.put("model", "deepseek-chat");
            params.put("stream", true);

            return WEB_CLIENT.post().uri("/chat/completions")
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer sk-e378cad3fe334f79b3f388a1003a3784")
                    .bodyValue(JSONUtil.toJsonStr(params))
                    .retrieve().bodyToFlux(String.class);

        } catch (Throwable e) {
            log.error("AI回复失败：", e);
            throw exception(AI_CHAT_REPLY_ERROR);
        }
    }
}
